<?php

namespace app\company\controller;

use app\company\validate\CompanyRoleValidate;
use app\service\traits\Crud;
use app\company\model\CompanyRole as CompanyRoleModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Response;

class CompanyRole extends Base
{
    private CompanyRoleModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new CompanyRoleModel();
        $this->validateClass = CompanyRoleValidate::class;
        $this->field         = 'id,name,status,role_key,role_sort,data_scope,create_time,remark';
        $this->append        = 'data_scope_text';
        $this->withSearch    = 'name,role_key,status,create_time';
        $this->isGs          = true;
    }

    public function format($list): mixed
    {
        return $list->each(function($item) {
            $item->menu_ids = $item->companyRoleMenus()->column('company_menu_id');
        });
    }


    /**
     * 筛选框
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function search(): Response
    {
        $param = request()->param();
        $sql   = $this->model;
        $sql   = $sql->gs()->withSearch($this->withSearch, $param);
        $field = 'id';
        if (request()->param('field')) $field .= ',' . request()->param('field');
        $list = $sql->field($field)->order($this->orderSort)->select();
        return $this->success('获取成功', compact('list'));
    }
}